const router = require("koa-router")();

const { getUserIdByContext } = require('../token')
const ArticleBasic = require('../../model/ArticleBasic')
const ArticleInfo = require('../../model/ArticleInfo')
const ArticleAttitude = require('../../model/ArticleAttitude')
const UseRead = require('../../model/UserRead')

const UUID = require('uuid')
// 获取搜索文章列表
router.get('/articles', async ctx  => {
    const user_id = await getUserIdByContext(ctx) // 获取用户id
    if (!user_id) {
        return { success: false, message: '用户未认证', status: 401 }
    }
    // 如果用户未登录 返回默认的频道数据
   let { page = 1, per_page = 10, status, channel_id , begin_pubdate,  end_pubdate  } = ctx.request.query
   page = parseInt(page) // 当前页码
   per_page = parseInt(per_page) // 每页条数
   // 条件
   let condition = { user_id }
   // 状态
   if (status !== undefined && status !== "") {
    condition = { ...condition, status }
   }
   if (channel_id !== undefined && channel_id !== "") {
    if (channel_id == 0) {
        channel_id = '11'
    }
    condition = { ...condition, channel_id }
   }
   let create_time = {}
   // 开始时间
   if (begin_pubdate) {
    create_time = { $gte: begin_pubdate  }
   }
   if (end_pubdate) {
    create_time = { ...create_time , $lte: end_pubdate  }
   }
   if (Object.keys(create_time).length) {
    condition = { ...condition, create_time }
   }
   const  total_count = await ArticleBasic.find(condition).countDocuments()
   const result = await ArticleBasic.find(condition).sort({"_id": -1}).skip((page - 1) * per_page).limit(per_page)
   const reads = await UseRead.find({}).lean()
   const attitudes = await ArticleAttitude.find({}).lean()
   ctx.status = 200
   const results = result.map(item => ({
       id: item.article_id,
       title: item.title,
       status: parseInt(item.status) ,
       comment_count: parseInt(item.comment_count) ,
       pubdate: item.create_time,
       cover: item.cover && item.cover.split(',').length ? { type: item.cover.split(',').length, images: item.cover.split(',')  } :{ type: 0, images: [] },
       like_count:  attitudes.filter(obj => obj.article_id  === item.article_id && obj.attitude == 1).length,
       read_count: reads.filter(obj => obj.article_id  === item.article_id).length
   }))
   return  { data: { page, per_page, results, total_count  } }
})
// 修改文章
router.put('/articles/:target', async ctx  => {
    const user_id = await getUserIdByContext(ctx) // 获取用户id
    // 是否存为草稿
    let { draft } = ctx.request.query
    const { target } = ctx.params
    let { title, channel_id, content, cover } = ctx.request.body
    if (!user_id) {
        return { success: false, message: '用户未认证', status: 401 }
    }
    if (!target) {
        return { success: false, message: '没有要传递的文章target', status: 400 }
    }
    if (!title || !content ) {
        return { success: false, message: '文章标题和文章内容不能为空', status: 400 }
    }
    if (!cover || (cover.type !== 0 && cover.type !== 1 &&  cover.type !== 3)) {
        return { success: false, message: '封面类型不正确', status: 400 }
    }
    if (channel_id == 0) {
        channel_id = '11'
    }
    let coverStr = cover.images && cover.images.length ? cover.images.join(',') : ''
 
    // 发表为正式文章  这里进行一下特殊处理 发表正式文章之后 => 先变成 待审核 => 1分钟之后 => 自动变成审核通过
    await ArticleBasic.findOneAndUpdate({ article_id: target }, { title, cover: coverStr, channel_id, update_time: Date.now(), status: draft == 'true' ? 0 : 1 } )
    await ArticleInfo.findOneAndUpdate({ article_id: target }, { content } )
    if (draft != 'true') {
        // 一分钟之后 待审核自动变成审核通过
        setTimeout(async function() {
            await ArticleBasic.findOneAndUpdate({ article_id: target }, {  status: 2 } )
        }, 60000)
    }
   return  { data: { id: target  } }
})
// 发布文章
router.post('/articles', async ctx  => {
    const user_id = await getUserIdByContext(ctx) // 获取用户id
    // 是否存为草稿
    let { draft } = ctx.request.query
    let { title, channel_id, content, cover } = ctx.request.body
    if (!user_id) {
        return { success: false, message: '用户未认证', status: 401 }
    }
    if (!title || !content ) {
        return { success: false, message: '文章标题和文章内容不能为空', status: 400 }
    }
    if (!cover || (cover.type !== 0 && cover.type !== 1 &&  cover.type !== 3)) {
        return { success: false, message: '封面类型不正确', status: 400 }
    }
    if (channel_id == 0) {
        channel_id = '11'
    }
    const article_id = UUID.v4()
    let coverStr = cover.images && cover.images.length ? cover.images.join(',') : ''
    // 发表为正式文章  这里进行一下特殊处理 发表正式文章之后 => 先变成 待审核 => 1分钟之后 => 自动变成审核通过
    await ArticleBasic.create({article_id, title, cover: coverStr, channel_id, comment_count: 0, user_id,  update_time: Date.now(), status: draft == 'true' ? 0 : 1 } )
    await ArticleInfo.create({ content, article_id } )
    if (draft != 'true') {
        // 一分钟之后 待审核自动变成审核通过
        setTimeout(async function() {
            await ArticleBasic.findOneAndUpdate({ article_id }, {  status: 2 } )
        }, 60000)
    }
   return  { data: { id: article_id  } }
})
// 删除文章
router.delete('/articles/:target', async ctx  => {
    const user_id = await getUserIdByContext(ctx) // 获取用户id
    const { target } = ctx.params

    // 是否存为草稿
    if (!user_id) {
        return { success: false, message: '用户未认证', status: 401 }
    }
    if (!target) {
        return { success: false, message: '要删除的文章id不能为空', status: 400 }
    }
    const { status } = await ArticleBasic.findOne({ article_id : target  }).lean()
    // if (status == 2 ) {
    //     return { success: false, message: '已发表的文章不能删除', status: 400 }
    // }
    // 发表为正式文章  这里进行一下特殊处理 发表正式文章之后 => 先变成 待审核 => 1分钟之后 => 自动变成审核通过
    await ArticleBasic.findOneAndDelete({ article_id : target } )
    await ArticleInfo.findOneAndDelete({ article_id : target } )
    return  {  }
})
// 获取文章详情
router.get('/articles/:target', async ctx  => {
    const user_id = await getUserIdByContext(ctx) // 获取用户id
    const { target } = ctx.params

    // 是否存为草稿
    if (!user_id) {
        return { success: false, message: '用户未认证', status: 401 }
    }
    if (!target) {
        return { success: false, message: '要获取的文章id不能为空', status: 400 }
    }
  
    // 发表为正式文章  这里进行一下特殊处理 发表正式文章之后 => 先变成 待审核 => 1分钟之后 => 自动变成审核通过
   const { article_id, title, channel_id, create_time, cover } = await ArticleBasic.findOne({ article_id : target } ).lean()
   const { content } =  await ArticleInfo.findOne({ article_id : target }).lean()
   const data = {
       id : article_id,
       title,
       channel_id: parseInt(channel_id), 
       content,
       cover: cover && cover.split(',').length ? { type: cover.split(',').length, images: cover.split(',')  } : { type: 0, images: [] },
       pub_date: create_time,
   }
    return  { data }
})
module.exports = router.routes();
